var express = require('express');
var router = express.Router();
var db = require('../config/db');
/* GET users listing. */
router.get('/login', function(req, res, next) {
 	var userName = req.query.name;
 	var password = req.query.password;
 	console.log(userName+password)
 	db.query('select * from user where name=? and password= ?',[userName,password])
 	.then(data=>{
 		if(data){
 			console.log(data)
 			res.cookie("userId",data[0].userId,{
 				path:'/',
 				maxAge:1000*60*60
 			});
 			res.cookie("name",data[0].name,{
 				path:'/',
 				maxAge:1000*60*60
 			});
 			res.json({status:200,message:'登录成功', result:{
                      userName:data[0].name
                  }})
 		}
 	})
});

router.get('/logout',function(req,res){
	res.cookie('userId','',{
		path:'/',
		maxAge:-1
	})
	res.json({
		status:200,
		message:'退出成功'
	})
})
//用户购物车列表
router.get('/cartList',function(req,res){
	var userId =req.cookies.userId;
	db.query('select * from cartList where userId=?',[userId])
	.then(data=>{
		var count=0;
		data.map(item=>{
			count+=item.productNum;
		})
		res.json({status:200,list:data,count:count})
	}).catch(e=>{
		res.json({status:400})
	})
})
/**
 * 购物车货物数量修改
 * @type {[type]}
 */
router.get('/addPro',function(req,res){
	
	var productId = req.query.productId;
	var productNum = req.query.productNum;
	if(req.cookies&&req.cookies.userId){
		var userId = 1;
		db.query('update cartlist set productNum =? where userId=? and productId = ?',[productNum,userId,productId])
		.then(data=>{
			res.json({status:200,message:'更新成功'})
		})
	}
})
/**
 * [exports description]
 * @type {[type]}
 */
module.exports = router;
